package de.mmis.core.base.event;

import de.mmis.core.base.ObjectDescriptor;
import de.mmis.core.base.abstracttree.Tree;

/**
 * generic observer wrapper serializing an incoming arbitrary event into a
 * {@link Tree} and fire it as a new (fixed type) event
 * 
 * @author Christian Koch
 * 
 * @param <E>
 *            type of the events to wrap
 */
public class GenericObserver<E extends Event> extends
		AbstractObservable<GenericObserverEvent> implements Observer<E> {
	private final Observable<E> observable;
	private final boolean explicit;

	@SuppressWarnings("unchecked")
	public GenericObserver(Object o, boolean explicit) {
		this.explicit = explicit;
		this.observable = (Observable<E>) o;
		this.observable.addObserver(this);
	}

	@Override
	public void notify(Observable<? extends E> sender, E event) {
		Tree exp = Tree.fromObject(event, explicit);
		fireEvent(new GenericObserverEvent(exp));
	}

	/**
	 * @return new generic observer class instance, or null, if object is not
	 *         Observable
	 */
	@SuppressWarnings("rawtypes")
	public static GenericObserver<?> createGenericObserver(ObjectDescriptor od,
			boolean explicit) {
		if (od.getObservableClass() == null)
			return null;
		return new GenericObserver(od.getObject(), explicit);
	}
}
